package com.ruoyi.system.service.impl;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.ProjectInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ProcurementDetailMapper;
import com.ruoyi.system.domain.ProcurementDetail;
import com.ruoyi.system.service.IProcurementDetailService;

import javax.validation.Validator;

/**
 * 明细Service业务层处理
 * 
 * @author xuliang
 * @date 2024-03-29
 */
@Service
public class ProcurementDetailServiceImpl implements IProcurementDetailService
{
    private static final Logger log = LoggerFactory.getLogger(ProcurementDetailServiceImpl.class);

    @Autowired
    private ProcurementDetailMapper procurementDetailMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询明细
     * 
     * @param id 明细主键
     * @return 明细
     */
    @Override
    public ProcurementDetail selectProcurementDetailById(Long id)
    {
        return procurementDetailMapper.selectProcurementDetailById(id);
    }

    /**
     * 查询明细列表
     * 
     * @param procurementDetail 明细
     * @return 明细
     */
    @Override
    public List<ProcurementDetail> selectProcurementDetailList(ProcurementDetail procurementDetail)
    {
        return procurementDetailMapper.selectProcurementDetailList(procurementDetail);
    }

    /**
     * 新增明细
     * 
     * @param procurementDetail 明细
     * @return 结果
     */
    @Override
    public int insertProcurementDetail(ProcurementDetail procurementDetail)
    {
        return procurementDetailMapper.insertProcurementDetail(procurementDetail);
    }

    /**
     * 修改明细
     * 
     * @param procurementDetail 明细
     * @return 结果
     */
    @Override
    public int updateProcurementDetail(ProcurementDetail procurementDetail)
    {
        return procurementDetailMapper.updateProcurementDetail(procurementDetail);
    }

    /**
     * 批量删除明细
     * 
     * @param ids 需要删除的明细主键
     * @return 结果
     */
    @Override
    public int deleteProcurementDetailByIds(Long[] ids)
    {
        return procurementDetailMapper.deleteProcurementDetailByIds(ids);
    }

    /**
     * 删除明细信息
     * 
     * @param id 明细主键
     * @return 结果
     */
    @Override
    public int deleteProcurementDetailById(Long id)
    {
        return procurementDetailMapper.deleteProcurementDetailById(id);
    }


    /**
     * 导入明细
     * @param detailList 明细
     * @param updateSupport 是否更新
     * @param operName 操作人
     * @return 结果
     */
    @Override
    public String importDetail(List<ProcurementDetail> detailList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(detailList) || detailList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ProcurementDetail detail : detailList)
        {
            try
            {
                // 验证是否存在该条数据
                ProcurementDetail p = procurementDetailMapper.selectProcurementDetailByContractCode(detail.getContractCode());
                if (StringUtils.isNull(p))
                {
                    BeanValidators.validateWithException(validator, detail);
                    detail.setCreateBy(operName);
                    detail.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                    procurementDetailMapper.insertProcurementDetail(detail);
                    successNum++;
                    successMsg.append("<br/>").append(successNum)
                            .append("、明细 ：").append(detail.getItemName())
                            .append(" ， 合同编号 ：").append(detail.getContractCode())
                            .append(" 导入成功");
                }
                else if (updateSupport)
                {
                    BeanValidators.validateWithException(validator, detail);
                    detail.setId(detail.getId());
                    detail.setUpdateBy(operName);
                    detail.setUpdateTime(DateUtils.getNowDate());
                    procurementDetailMapper.updateDetailByCode(detail);
                    successNum++;
                    successMsg.append("<br/>").append(successNum)
                            .append("、明细 ：").append(detail.getItemName())
                            .append(" ， 合同编号 ：").append(detail.getContractCode())
                            .append(" 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum)
                            .append("、明细 ：").append(detail.getItemName())
                            .append(" ， 合同编号 ：").append(detail.getContractCode())
                            .append(" 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、明细 ：" + detail.getItemName() + (" ， 合同编号 ：") + detail.getContractCode()
                        + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "部分导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int countDetailByContractCodeAndNumber(ProcurementDetail detail) {
        return procurementDetailMapper.countDetailByContractCodeAndNumber(detail);
    }

}
